<template>
	<view class="content">
		<view class="xiaode-tips" v-if="!showLogin">
			<view class="tips">
				<text>欢迎来到晓德助手</text><br>
				<text>{{loginTips}}</text>
				<view class="login-tips">
					<!-- <text>正在登录中</text> -->
					<image src="/static/loginLoading.gif" mode="aspectFit"></image>
				</view>
			</view>
		</view>
		<view v-else-if="showLogin">
			<view class="logo">
				<image src="/static/u16.png"  mode="aspectFit"></image>
			</view>
			<form @submit="loginHandle">
				<view class="uni-form-item uni-column2">
					<view class="left">
						<view class="title" style="letter-spacing: 1em">账号</view>
						<input class="uni-input" :value="account" name="input" @input="accountInput" @focus="accountFocus" placeholder="请输入账号" />
					</view>
					<uni-icons v-if="accounts.length>0" type="bottom"  :style="{transform: `rotate(${show_accounts?180:0}deg)`}" @click="show_accounts=!show_accounts"></uni-icons>
					<view :class="[{'dialog-bubble': show_accounts}, 'account-list']">
						<view class="at-item" v-for="(account, i) in accounts" :key="i" @click="choiceAccount(i)">
							{{account}}
						</view>
					</view>
				</view>
				<view class="uni-form-item uni-column2">
					<view class="left">
						<view class="title" style="letter-spacing: 1em;">密码</view>
						<input class="uni-input" :password="show_password" :value="password" name="input" @input="passInput" placeholder="请输入密码" />
					</view>
					<uni-icons :type="show_password?'eye-slash-filled':'eye-filled'"  @click="show_password=!show_password"></uni-icons>
				</view> 
				<button form-type="submit" class="stu-btn-text">{{login_text}}</button>  
			</form>
			<view class="keep-password">
				<checkbox-group @change="change">
					<checkbox value="1" :checked="false" color="#333" style="transform:scale(0.6);" />
				</checkbox-group>
				<view>30天内免登录<text class="line"></text><text @click="retPassword">忘记密码</text></view>
			</view>
		</view>
	</view>
</template>
<script>
	import uniRequest from 'uni-request';
	import md5 from '@/static/md5.min.js'
	let members_info = {}
export default {
    data() {
        return {
			showLogin: false,
			page: ["角色选择","教师登录","学生登录"],
			banDingCode: '',
			currentWebview: null,
			account: '',
			password: '',
			show_password: true,
			show_accounts: false,
			accounts:[], //账号选择列表
			rememberPassword: '',
			login_text: '登录',
			loginTips: ''
        }   
	},
	onLoad(options) {
		
		// #ifdef APP-PLUS
		this.currentWebview = this.$scope.$getAppWebview()
		// #endif
		uni.setNavigationBarTitle({
			title: '用户登录'
		})
		this.getAccounts();
		// #ifdef H5
		let code = getUrlParam(location.href).code||''
		if(code){
			this.userLogin(code);
			return
		}
		// #endif
		const tokenObj = uni.getStorageSync('tokenObj');
        if(tokenObj&&tokenObj.token){
            this.api.get('user/getMeInfo').then(res=>{
                let info = res.data.user
                getApp().globalData.userInfo = info;
                if(info.user_type == 1){
                    uni.switchTab({
                        url: '/pages/teachers/index'
                    })
                }else{
                    uni.switchTab({
                        url: '/pages/student/task-page'
                    })
                }
                
            })
        }else{
			this.showLogin = true
		}
	},
    onShow(){
		// #ifdef APP-PLUS
		
		let tokenObj = uni.getStorageSync('tokenObj');
		
		if(tokenObj&&tokenObj.token){
			uni.showLoading({
				title: '加载中',
				mask: true
			})
			let pathUrl = '/pages/teachers/index'
			if(tokenObj.userType==2){
				pathUrl = '/pages/student/task-page';
			}
			this.api.get('user/getMeInfo').then(res=>{
				if(res.data.state != 'ok'){
					uni.hideLoading()
				}
				
				// console.log(979797, res)
				let info = res.data.user
				if(info.user_type==2){
					this.utils.setSTabBar();
				}else{
					this.utils.setTTabBar()
				}
				getApp().globalData.userInfo = info;
				
				
				uni.switchTab({
					url: pathUrl,
					success: ()=>{
						uni.hideLoading()
					}
				})
			})
			return;
		}
		// #endif
        if(getApp().globalData.msgTipsTrim){
			clearInterval(getApp().globalData.msgTipsTrim);
		}
    },
	methods: {
		change(e){
			this.rememberPassword = e.detail.value[0];
		},
		accountInput(eve){
			this.account = eve.detail.value;
		},
		accountFocus(){
			this.show_accounts = false;
		},
		passInput(eve){
			this.password = eve.detail.value;
		},
		loginHandle(){
			// #ifdef H5
			// if(HWH5.callMethod){
			// 	HWH5.getAuthCode().then(data => {
			// 		let code = data.code;
			// 		this.userLogin(code);
			// 	}).catch(error => {
			// 		// console.log(140, error)
			// 	});
			// }else{
				this.userLogin();
			// }
			// #endif
			// #ifdef APP-PLUS
			this.userLogin();
			// #endif
		},
		userLogin(code){
			let params = {}, loginPath = 'user/login'
			if(code){
				params = {
					code: code,
                	platform: 2
				}
				this.loginPost(params, loginPath)
				return
			}
			let tips = '';
			let pwLen = this.password.length;
			if(!this.account){
				tips = `账号不能为空`
			}else if(!this.password){
				tips = '密码不能为空'
			}else if(pwLen<6 || pwLen>30){
				tips = '密码不正确'
			}
			if(tips!=''){
				uni.showToast({
					title: tips,
					icon: 'none',
					mask: true,
					position: 'bottom'
				})
				return;
			}
			params = {
				account: this.account,
				password: md5(this.password),
				// #ifdef H5
				platform: 3,
				// #endif
				// #ifdef APP-PLUS
				platform: 1
				// #endif
			}
			if(this.banDingCode){
				loginPath = 'user/binDingWeLink'
				params.banDingCode = this.banDingCode
			}
			this.loginPost(params, loginPath)
			// 13072859112  123456
			
			
		},
		// 登录返回处理
		loginPost(params, loginPath){
			this.api.post(loginPath, params).then(res=>{
				let dataInfo = res.data;
				if(dataInfo.state == 'fail'){
					// this.loginTips = data.errorMsg
					//  this.utils.showToast('请先绑定WElink')
					//  this.login_text = '绑定并登录'
                    //     this.showLogin = true
					uni.showToast({
						title: dataInfo.error.msg || '',
						icon: 'none',
						mask: true,
						position: 'bottom'
					});
				}else if(dataInfo.state == 'ok'){
					if(dataInfo.banDingCode){
                        this.utils.showToast('请先绑定WElink')
						this.login_text = '绑定并登录'
                        this.showLogin = true
                        return
                    }
					this.login_text = '登录中···'
					this.getBaseInfo()
					uni.removeStorageSync('monthActivityAll');
					//保存koken信息
					let info = dataInfo.user
					let item = dataInfo.token;
					getApp().globalData.isStudent = info.user_type==2?true:false
					let tokenObj = {
						userType: info.user_type,
						token: item,
						userId: info.id,// 使用用户id
						accountId: info.accountId
					}
					if(this.rememberPassword!=1){
						tokenObj.loginTime =  new Date().getTime()
					}
					uni.setStorageSync('tokenObj', tokenObj);
					uniRequest.defaults.headers.common['Token'] = item;
					// 判断添加账号
					let index = this.accounts.indexOf(this.account);
					if(index==-1){
						this.accounts.unshift(this.account);
					}else{
						this.accounts.splice(index,1);
						this.accounts.unshift(this.account);
					}
					
					getApp().globalData.userInfo = info;
					//保存账号
					uni.setStorageSync('uAccounts', this.accounts);
					this.getfindMembers(dataInfo.usertype)

					// 修改密码
					// if(info.reset){
					// 	uni.navigateTo({
					// 		url: '/pages/personalInfo/edit-password?type=pass&edit=1'
					// 	})
					// 	return;
					// }
					//触发登陆事件
					this.getWsToken()
					
					
				}
				
			})
		},
		getWsToken(){
			this.api.get('user/getWsToken').then(res=>{
				if(res.data.state!='ok') return
				let info = uni.getStorageSync('tokenObj')
				info.wsToken = res.data.wsToken
				uni.setStorageSync('tokenObj', info);
				uni.$emit('login',{});
			})
		},
		getBaseInfo(){
			this.api.get('base/getBaseInfo').then(res=>{
				let data = res.data || {}
				let orgGrades = data.orgGrades;
				let newOrgGraders = []
				for (const key in orgGrades) {
					let list = orgGrades[key].class;
					if (list.length>0) {
						for(let i=0; i<list.length; i++){
							let obj = {}, item = list[i]
							obj[item.id] = `${orgGrades[key].name}${item.name}`
							newOrgGraders.push(obj)
						}
						
					}
				}
				
				data.newOrgGraders = newOrgGraders;
				getApp().globalData.baseInfo = data;
			})
		},
		getExample(){
			this.api.get('sExample/findBindExample').then(res=>{
				const example = res.data.example || {};
				if(example.id){
					uni.switchTab({
						url: '/pages/student/task-page'
					})
				}else{
					uni.navigateTo({
						url: '/pages/student/select-example'
					})
				}
			})
		},
		getAccounts(){
			this.accounts = uni.getStorageSync('uAccounts') || [];
			this.account = this.accounts[0] || '';
		},
		choiceAccount(index){
			this.show_accounts = false;
			this.account = this.accounts[index];
		},
		retPassword(){
			uni.navigateTo({
				url: '/pages/index/retrieve-password?account='+this.account
			})
		},
		
		getUserInfo(){
			this.api.get('user/findUserInfo').then(res=>{

			})
		},
		getfindMembers(type){
			this.api.get('user/findUserInfo').then(res=>{
				if(res.data.state != 'ok') return;
				members_info = Object.assign(res.data.admins, res.data.students)
				uni.setStorageSync('allFindMembers', members_info)
				//跳转指定页面
				if(type == 1){
					uni.$emit('getMsgTips', res => {})
					uni.switchTab({
						url: '/pages/teachers/index'
					})
					
				}else{
					this.getExample();
				}
				
				
			})
		}
		
	}
}
function getUrlParam(sUrl) {
	let indexStart = sUrl.indexOf('?')
	if(indexStart==-1){return {}};
	let k  = sUrl.slice(indexStart+1);
	let x = k.replace(/&/g, '","').replace(/=/g, '":"');
	let y = '{"' + x + '"}';
	
	return JSON.parse(y);
}
</script>
<style lang="less">
	.content{
		display: flex;
		flex-direction: column;
		justify-content: center;
		padding: 0 32rpx;
	}
	
	.logo{
		margin: 180rpx 0 140rpx 0;
		text-align: center;
		image{
			width: 200rpx;
			height: 200rpx;
		}
	}
	
	.xiaode-tips{
		min-height: calc(100vh - 44px);
		display: flex;
		align-items: center;
		justify-content: center;
		.tips{
			font-size: 32rpx;
			line-height: 60rpx;
			text-align: center;
        }
	}
	
	.stu-btn-text{
		display: block;
		text-align: center;
		margin: 80rpx 0rpx 0;
		font-size: 28rpx;
	}
	
	.uni-form-item{
		position: relative;
		height: 70rpx;
		display: flex;
		align-items: center;
		border-bottom: 2rpx solid #f2f2f2;
		margin-bottom: 40rpx;
		padding: 0 32rpx;
		.title{
			white-space: nowrap;
			margin-right: 24rpx;
			width: 84rpx;
		}
		&.uni-column2{
			justify-content: space-between;
			.left{
				display: flex;
				align-items: center;
				width: 90%;
			}
		}
		.uni-input{
			width: 100%;
			font-size: 28rpx;
		}
		
		.account-list{
			position: absolute;
			top: 90rpx;
			right: 0;
			left: 0;
			height: 0;
			overflow: hidden;
			text-align: center;
			background-color: #f5f5f5;
			border-radius: 16rpx;
			z-index: 1;
			transition: all .1s;
			&.dialog-bubble{
				padding: 24rpx 0;
				height: auto;
				max-height: 300rpx;
				overflow-y: scroll;
			}
			.uni-icons{
				transition: all .1s;
			}
		}
		.at-item{
			height: 80rpx;
			line-height: 80rpx;
			border-bottom: 2rpx solid #e4e4e4;
			&:last-child{
				border: none;
			}
		}
	}
	.keep-password{
		margin-top: 40rpx;
		text-align: right;
		font-size: 26rpx;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		/deep/uni-checkbox:not([disabled]) .uni-checkbox-input:hover{
			border-color: #333;
		}
		/deep/uni-checkbox .uni-checkbox-input{
			border-color: #333;
		}
		.line{
			display: inline-block;
			width: 2rpx;
			height: 36rpx;
			background-color: #7f7f7f;
			margin: 0 12rpx;
			vertical-align: text-top;
		}
	}
	
	
</style>